package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService service;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService flavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        log.info("菜品列表查询,入参:页码:{},每页显示条数:{},搜索条件:{}", page, pageSize, name);
        //1. 构建分页模型
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //2. 组装查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        //3. 组装排序条件
        wrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getPrice);
        //4. 分页查询
        service.page(dishPage, wrapper);

        //5. 处理菜品分类名称
        Page<DishDto> dishDTOPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDTOPage);

        List<Dish> dishRecords = dishPage.getRecords();
        List<DishDto> dishDtoRecords = dishRecords.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDTOPage.setRecords(dishDtoRecords);

        //返回结果
        return R.success(dishDTOPage);
    }

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("进行添加菜品处理,接收到入参:{}", dishDto.toString());

        service.add(dishDto);

        //新增完成后, 清除对应分类缓存的菜品数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("添加菜品成功!");
    }

    @PutMapping
    public R<String> edit(@RequestBody DishDto dishDto) {
        log.info("进行修改菜品处理,接收到入参:{}", dishDto.toString());

        service.updateWithFlavors(dishDto);

        //新增完成后, 清除对应分类缓存的菜品数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功!");
    }

    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        log.info("查询菜品详情,入参:{}", id);
        Dish dish = service.getById(id);

        //根据菜品id查询对应口味数据
        LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper();
        flavorQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = flavorService.list(flavorQueryWrapper);

        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(flavors);

        return R.success(dishDto);
    }

    /**
     * 根据分类id查询菜品信息
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId) {
        log.info("根据分类id查询菜品信息, 入参:{}", categoryId);

        //先查redis,redis有直接用
        String key = "dish_" + categoryId + "_1";
        List<DishDto> dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dtoList != null){
            return R.success(dtoList);
        }

        //redis没有则查询数据库
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper();
        //根据分类id查询菜品
        wrapper.eq(categoryId != null, Dish::getCategoryId, categoryId);
        //筛选出状态为1(起售状态)的菜品
        wrapper.eq(Dish::getStatus, 1);
        //设置排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = service.list(wrapper);

        //数据处理,封装口味数据
        dtoList = list.stream().map(
                dish -> {
                    DishDto dishDto = new DishDto();
                    //同步菜品数据
                    BeanUtils.copyProperties(dish, dishDto);
                    //查询菜品对应的口味数据
                    Long dishId = dish.getId();
                    LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
                    qw.eq(DishFlavor::getDishId, dishId);
                    qw.orderByDesc(DishFlavor::getUpdateTime);
                    List<DishFlavor> flavors = flavorService.list(qw);
                    dishDto.setFlavors(flavors);
                    return dishDto;
                }
        ).collect(Collectors.toList());

        //将数据存入redis管理
        redisTemplate.opsForValue().set(key,dtoList);

        return R.success(dtoList);
    }
    /*public R<List<Dish>> list(Long categoryId) {
        log.info("根据分类id查询菜品信息, 入参:{}", categoryId);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper();
        //根据分类id查询菜品
        wrapper.eq(categoryId != null,Dish::getCategoryId,categoryId);
        //筛选出状态为1(起售状态)的菜品
        wrapper.eq(Dish::getStatus,1);
        //设置排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = service.list(wrapper);
        return R.success(list);
    }*/


}
